/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

import { hvigorCore } from '@ohos/hvigor';

import { InjectConst } from '../../const/inject-const.js';
import { getJson5Obj } from '../../utils/json-util.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { TaskNames } from '../common/task-names.js';
import { CompileResource } from '../compile-resource.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { OhosHapTask } from '../task/ohos-hap-task.js';
import CommonTask = TaskNames.CommonTask;
import fse from 'fs-extra';
import path from 'path';

import { CommonConst } from '../../const/common-const.js';
import { ModuleJson } from '../../options/configure/module-json-options.js';

/**
 * 单元测试 stage模型中替换的入口文件
 */
export class ReplaceUnitTestIndexFile extends OhosHapTask {
  private _log: OhosLogger = OhosLogger.getLogger(ReplaceUnitTestIndexFile.name);
  private PAGE_JSON = 'main_pages';
  private PAGE_JSON_FILE = `${this.PAGE_JSON}.json`;
  private PAGE_JSON_RESOURCE = `$profile:${this.PAGE_JSON}`;

  constructor(taskService: TargetTaskService) {
    super(taskService, CommonTask.REPLACE_UNIT_TEST_INDEX_FILE);
  }

  initTaskDepends(): void {
    this.declareDepends(CompileResource.name);
  }

  protected doTaskAction() {
    const moduleJsonPath: string = path.resolve(this.pathInfo.getIntermediatesRes(), CommonConst.MODULE_JSON);
    const pageJsonPath: string = path.resolve(this.pathInfo.getIntermediatesResProfilePath(), this.PAGE_JSON_FILE);
    if (this.moduleModel.isHarModule()) {
      this.writeModuleJson(moduleJsonPath);
      this.writeMainPages(pageJsonPath);
      return;
    }
    const moduleJson: ModuleJson.ModuleOptObj = getJson5Obj(moduleJsonPath);
    const pageStr: string = moduleJson?.module?.pages;
    if (this.moduleModel.isHspModule()) {
      if (!pageStr) {
        this.writeModuleJson(moduleJsonPath);
      }
      this.writeMainPages(pageJsonPath);
      return;
    }

    // 如果feature 里 module.json 中 没有 mainPage 字段，加一下
    if (this.moduleModel.isHapModule() && !pageStr) {
      this.writeModuleJson(moduleJsonPath);
      this.writeMainPages(pageJsonPath);
    }

    const unitTestIndex: string | undefined = hvigorCore.getExtraConfig().get(InjectConst.UNIT_TEST_REPLACE_PAGE);
    if (unitTestIndex) {
      this.replacePagesInPreview(this._log, [unitTestIndex]);
    }
  }

  private writeModuleJson(filePath: string) {
    let moduleInfo;
    if (fse.existsSync(filePath)) {
      moduleInfo = fse.readJsonSync(filePath);
      if (moduleInfo?.module) {
        moduleInfo.module.pages = this.PAGE_JSON_RESOURCE;
      }
    } else {
      const processProfileModuleJsonPath = this.targetData.getPathInfo().getIntermediatesProcessProfile();
      moduleInfo = getJson5Obj(processProfileModuleJsonPath);
      if (moduleInfo?.module) {
        moduleInfo.module.pages = this.PAGE_JSON_RESOURCE;
      } else {
        moduleInfo = {
          module: {
            pages: this.PAGE_JSON_RESOURCE,
          },
        };
      }
    }
    fse.ensureFileSync(filePath);
    fse.writeJSONSync(filePath, moduleInfo);
  }

  private writeMainPages(filePath: string) {
    const unitTestIndex: string | undefined = hvigorCore.getExtraConfig().get(InjectConst.UNIT_TEST_REPLACE_PAGE);
    if (!unitTestIndex) {
      return;
    }
    const fileContent = {
      src: [unitTestIndex],
    };
    fse.ensureFileSync(filePath);
    fse.writeJSONSync(filePath, fileContent);
  }
}
